//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using CommunityServer.Components;

namespace CommunityServer.Components
{
	/// <summary>
	/// Summary description for Rating.
	/// </summary>
	public class Rating
	{
		#region Private Members...
		private RatingType ratingType;
		private int itemID;
		private User user;
		private int newValue = 0;
		private int oldValue = 0;
		private bool wasRefreshed = false;
		#endregion

		#region Constructors...
		/// <summary>
		/// Default constructor.
		/// </summary>
		public Rating()
		{
		}


		/// <summary>
		/// Creates a full rating (excluding an old rating value)
		/// </summary>
		/// <param name="ratingType">The type of item being rated</param>
		/// <param name="itemID">The id of the item being rated</param>
		/// <param name="user">The user responsible for the rating</param>
		/// <param name="rating">The value of the rating</param>
		public Rating(RatingType ratingType, int itemID, User user, int rating)
		{
			this.ratingType = ratingType;
			this.itemID = itemID;
			this.user = user;
			this.newValue = rating;
		}
		#endregion

		#region Properties...
		/// <summary>
		/// The type of item being rated
		/// </summary>
		public RatingType RatingType
		{
			get { return ratingType; }
			set { ratingType = value; }
		}


		/// <summary>
		/// The id of the item being rated
		/// </summary>
		public int ItemID
		{
			get { return itemID; }
			set { itemID = value; }
		}


		/// <summary>
		/// The user responsible for the rating
		/// </summary>
		public User User
		{
			get { return user; }
			set { user = value; }
		}


		/// <summary>
		/// The value of the rating
		/// </summary>
		public int Value
		{
			get { return newValue; }
			set { newValue = value; }
		}


		/// <summary>
		/// The previous value of the rating
		/// </summary>
		public int OldValue
		{
			get { return oldValue; }
			set { oldValue = value; }
		}
		#endregion

		#region Methods...
		/// <summary>
		/// Determines if the rating has changed
		/// </summary>
		/// <returns></returns>
		public bool HasChanged()
		{
			// Since refresh hits the db, only do it once
			if (!wasRefreshed)
				Refresh();

			// Since 0 is default, we don't know if it's new or changed
			return ((Value != OldValue) || (Value == 0));
		}


		/// <summary>
		/// Fetches the old value of the rating (from database)
		/// </summary>
		public void Refresh()
		{
			OldValue = Ratings.GetRating(RatingType, ItemID, User.UserID);
			wasRefreshed = true;
		}
		#endregion
	}
}
